<template>
    <div class="search-input">
        <input class="c-form-control" type="text" :placeholder="placeholder" @input="search" ref="input" @focus="showList = true" @click.stop/>
        <ul v-if="list.length > 0" v-show="showList">
            <li v-for="item in list" @click="select(item)">{{ textKey ? item[textKey] : item }}</li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: 'searchInput',
        data(){
            return {
                timing: null,
                showList: false,
            }
        },
        props: {
            placeholder: { type: String, default: '' },
            list: { type: Array, default: () => []},
            textKey: { type: String }
        },
        watch: {
            showList(val){
                if(val){
                    this.$root.$el.addEventListener('click', ()=>{
                        this.showList = false;
                    });
                }else{
                    this.$root.$el.removeEventListener('click',  ()=>{
                        this.showList = false;
                    });
                }
            },
        },
        methods: {
            search(show){
                clearTimeout( this.timing );
                this.timing = setTimeout(
                    () => {
                        let value = this.$refs.input.value;
                        this.$emit('search', value);
                        this.showList = !!show;
                    }, 350
                );
            },
            select(item){
                this.$refs.input.value = this.textKey ? item[this.textKey] : item;
                this.$emit('select', item);
                this.showList = false;
                this.search(false);
            },
        },
    }
</script>

<style lang="scss">
    .search-input{
        position: relative;display: inline-block;
        ul{position: absolute;top: 33px;left: -1px;width: 100%;background: #fff;border-radius: 4px;padding: 4px 0;z-index: 9;border: 1px solid #afb8bd;max-height: 300px;overflow: auto;}
        li{display: block;padding: 0 6px;line-height: 28px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;color: #293134;cursor: pointer;}
        li:hover{background: #d9e3ec;}
        li.selected{color: #47bac1;}
    }
</style>
